package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.DataVo;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DataVo;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author syl
 * @date 2025-05-30
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;


    @Autowired
    private IDeviceDataService deviceDataService;
    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private TokenService tokenService;  //这是zzyl-framework模块中的

    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        String code = dto.getCode();
        String phoneCode = dto.getPhoneCode();

        // 调用微信接口返回openid
        String openid = wechatService.getOpenid(code);

        // 根据openid查询客户信息
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);

        String phone = wechatService.getPhone(phoneCode); //这里要注意获取手机号用的是phoneCode
        if(familyMember==null){
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            //从DEFAULT_NICKNAME_PREFIX随机挑选一个 + 手机号的后四位 0-8
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()))+phone.substring(7));
            familyMember.setOpenId(openid);
            familyMemberMapper.insert(familyMember);
        }else{
            // 这个用户是否修改过手机号
            if (!StrUtil.equals(familyMember.getPhone(),phone)) {
                familyMember.setPhone(phone);
            }
            familyMemberMapper.updateById(familyMember);

        }
        // 根据用户ID和昵称生成Jwt的token
        Map<String, Object> map = new HashMap();
        map.put("id", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map); //这里注意把tokenService.createToken改成public
        LoginVo  loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {

        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceData::getIotId, iotId);
        queryWrapper.orderByDesc(DeviceData::getAlarmTime);
        queryWrapper.last("limit 4");
        List<DeviceData> list = deviceDataService.list(queryWrapper);
        List<DeviceDataVo> dataVos = new ArrayList<>();
        for (DeviceData data : list) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(data.getFunctionId());
            deviceDataVo.setEventTime(data.getAlarmTime());
            deviceDataVo.setValue(data.getDataValue());
            dataVos.add(deviceDataVo);
        }
        return dataVos;
    }

    @Override
    public List<DeviceDataVo> queryDeviceDataListByDay(DeviceDataDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataVo> voList = familyMemberMapper.getHour(dto.getIotId(), dto.getFunctionId(), startTime, endTime);
        List<DeviceDataVo> list = new ArrayList<>();
        for (int i = 0; i < 25; i++) {
            final int finalHour = i;
            DeviceDataVo deviceDataVo = voList.stream().filter(vo -> vo != null && vo.getHour() != null && vo.getHour() == finalHour).findFirst().orElse(null);
            if (deviceDataVo != null) {
                list.add(deviceDataVo);
            } else {
                DeviceDataVo deviceDataVo1 = new DeviceDataVo();
                deviceDataVo1.setDateTime(String.format("%02d:00", finalHour));
                deviceDataVo1.setDataValue(50.0);
                list.add(deviceDataVo1);
            }
        }
        return list;
    }

    @Override
    public List<DataVo> queryDeviceDataListByWeek(DeviceDataDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataVo> voList = familyMemberMapper.queryDeviceDataListByWeek(dto.getIotId(), dto.getFunctionId(), startTime, endTime);
        List<DataVo> list = new ArrayList<>();
        for (DeviceDataVo deviceDataVo : voList) {
            if (deviceDataVo !=null) {
                DataVo dataVo = new DataVo();
                dataVo.setDateTime(deviceDataVo.getDateTime());
                dataVo.setDataValue(deviceDataVo.getDataValue());
                list.add(dataVo);
            }
        }
        return list;
    }

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

}
